package com.lazydong.apiforward.gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

@Component
public class CustomDataShowGlobalFilter implements GlobalFilter, Ordered {

    private static final List<CustomGlobalFilter> CUSTOM_GLOBAL_FILTERS = new ArrayList<>();

    @Autowired(required = false)
    private List<CustomGlobalFilter> autoCustomGlobalFilterList;

    @PostConstruct
    public void init() {
        ServiceLoader<CustomGlobalFilter> dataShowGlobalServiceLoader = ServiceLoader.load(CustomGlobalFilter.class);
        dataShowGlobalServiceLoader.forEach(CUSTOM_GLOBAL_FILTERS::add);
        if (autoCustomGlobalFilterList != null && !autoCustomGlobalFilterList.isEmpty()) {
            CUSTOM_GLOBAL_FILTERS.addAll(autoCustomGlobalFilterList);
        }
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        ServerHttpRequest request = exchange.getRequest();
        CUSTOM_GLOBAL_FILTERS.forEach(temp -> temp.beforeRequest(request, route));
        CUSTOM_GLOBAL_FILTERS.forEach(temp -> temp.webExchange(exchange));
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            ServerHttpResponse response = exchange.getResponse();
            CUSTOM_GLOBAL_FILTERS.forEach(temp -> temp.afterResponse(response));
        }));
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
